package com.atguigu.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.yygh.cmn.listener.DictListener;
import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.common.handler.YyghException;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl
        extends ServiceImpl<DictMapper, Dict>
        implements DictService {

    @Autowired
    private DictListener dictListener;

    //根据数据id查询子数据列表
    @Override
    //通过注解添加redis缓存
    //k:v   k=dict::selectIndexList  v=List<Dict>
    @Cacheable(value = "dict", key = "'selectIndexList'+#id")//拼接差值表达式  +#id
    public List<Dict> findChildData(Long id) {
        //1.根据id设置查询条件
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        //2.查询集合数据
        List<Dict> dictList = baseMapper.selectList(wrapper);
        //3.遍历集合，查询是否包含子节点
        dictList.forEach(item -> {  //item 自定义的名字
            //isChildren方法： 查询是否包含子节点  ↓↓↓
            boolean isChildren = this.isChildren(item.getId());
            item.setHasChildren(isChildren);
        });
        return dictList;
    }

    //查询是否包含子节点
    private boolean isChildren(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        Integer count = baseMapper.selectCount(wrapper);
        return count > 0;
    }

    //导出（数据）
    @Override
    public void exportData(HttpServletResponse response) {
        try {
            //1设置response属性
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            //2调用方法查询所有字典数据List<Dict>
            List<Dict> dictList = baseMapper.selectList(null);
            //3遍历集合，类型转化List<Dict> =》List<DictEeVo>
            List<DictEeVo> dictEeVoList = new ArrayList<>();
            for (Dict dict : dictList) {
                DictEeVo dictEeVo = new DictEeVo();
                //dictEeVo.setId(dict.getId());
                //借助BeanUtils工具，copyProperties复制对象属性(A复制给B)
                BeanUtils.copyProperties(dict, dictEeVo);
                dictEeVoList.add(dictEeVo);
            }
            //4调用工具导出文件
            ServletOutputStream outputStream = response.getOutputStream();//getOutputStream 获取输出流
            EasyExcel.write(outputStream, DictEeVo.class)
                    .sheet("数据字典").doWrite(dictEeVoList);//sheet表(自定义表名)
        } catch (IOException e) {
            e.printStackTrace();
            throw new YyghException(20001, "导出文件失败");
        }

    }

    //导入（文件）
    @Override
    public void importData(MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();//获取输入流
            //EasyExcel.read(InputStream inputStream,@Nullable Class head,@Nullable ReadListener readListener)
            //EasyExcel.读(流         ，类(可空)       ，监听器         .表()   .读方法()
            EasyExcel.read(inputStream, DictEeVo.class, dictListener).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            throw new YyghException(20001, "导入数据失败");
        }

    }

    //获取数据字典名称
    @Override
    public String getNameByParentDictCodeAndValue(String parentDictCode, String value) {
        //1.判断是国标还是自定义
        if (StringUtils.isEmpty(parentDictCode)) { //为空则是国标
            //2.国标数据查询
            Dict dict = baseMapper.selectOne(
                    new QueryWrapper<Dict>().eq("value", value) // value 值
            );
            if (dict != null) {
                return dict.getName();
            }
        } else {
            //3.自定义数据查询
            //  3.1跟据parentDictCode查询字典数据
            Dict parentDict = this.getDictByDictCode(parentDictCode);
            //  参数判断是否为空
            if (null == parentDict) return "";
            //  3.2跟据parentId＋value查询字典数据
            Dict dict = baseMapper.selectOne(
                    new QueryWrapper<Dict>()
                            .eq("parent_id", parentDict.getId()) //主键id
                            .eq("value", value) // value 值
            );
            if (dict != null) {
                return dict.getName();
            }
        }
        return "";  //查询不到，传入空串
    }

    /**
     * 根据dicode查询下层节点信息
     *
     * @param dictCode 医院编码
     */
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        //1、跟据dictCode查询父节点信息
        Dict parentDict = this.getDictByDictCode(dictCode);
        if (null == parentDict) return null;
        //2、跟据父节点id查询子节点列表
        List<Dict> list = this.findChildData(parentDict.getId());
        return this.findChildData(parentDict.getId());
    }

    //跟据DictCode查询字典数据
    private Dict getDictByDictCode(String parentDictCode) {
//        Dict dict = baseMapper.selectOne(
//                new QueryWrapper<Dict>().eq("dict_code", parentDictCode) // value 值
//        );

        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code", parentDictCode);
        Dict codeDict = baseMapper.selectOne(wrapper);
        return codeDict;
    }


}
